import * as Sequelize from "sequelize";
import { Application } from "egg";

interface VersionAttributes {
  app_id: string;
  id: string;
  version_name: string;
  cacheKey?: string;
  platform: string;
    remark?: string;
    create_user_id: string;
    modify_user_id: string;
  create_time: string;
  modify_time: string;
}

type VersionInstance = Sequelize.Instance<VersionAttributes> &
  VersionAttributes;

export default (app: Application) => {
  const { STRING, UUID, UUIDV4, DATE, NOW, CHAR } = app.Sequelize;
  const attributes: SequelizeAttributes<VersionAttributes> = {
    app_id: { type: UUID, primaryKey: false, allowNull: false },
    id: {
      type: UUID,
      primaryKey: true,
      allowNull: false,
      defaultValue: UUIDV4
    },
    version_name: { type: STRING(50), allowNull: false },
    cacheKey: { type: STRING(50), allowNull: true },
    platform: { type: CHAR(3), allowNull: true },
      remark: { type: STRING(200), allowNull: false },
      create_user_id: { type: UUID, allowNull: false },
      modify_user_id: { type: UUID, allowNull: false },
      create_time: { type: DATE, allowNull: false, defaultValue: NOW },
      modify_time: { type: DATE, allowNull: false, defaultValue: NOW }
  };
  const model = app.model.define<VersionInstance, VersionAttributes>(
    "Version",
    attributes,
    {
      tableName: "t_app_version"
    }
  );
  model.associate = () => {
    app.model.models.Version.belongsTo(app.model.models.App, {
      foreignKey: "app_id", targetKey: "id"
    });
    app.model.models.Version.hasMany(app.model.models.Package, {
      foreignKey: "version_id", sourceKey: "id"
    });
  };
  return model;
};
